package com.sunny.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Sunny on 2016/4/21.
 */
public class FileUtils {


    static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 递归遍历文件夹，找到.json文件，进行解析，得到result_rows 最大记录数，然后显示文件路径
     * @param dir
     * @return   List<JsonNode>   每个jsonNode下还可能存在子node。需要遍历出来进行处理。
     */
    public  static Integer readDirectory(String dir) {
        //List<JsonNode> list = new ArrayList<>();
        Long startTime = System.currentTimeMillis();
        File[] testFile = new File(dir).listFiles();
        Integer totalNum = 0;
        for (int i = 0; i < testFile.length; i++) {
            //  if( i < 3){  //测试 先读取一个
            if (testFile[i].isFile()) {
                //文件处理代码...
                File file = testFile[i];
                if(fileFilter(file,"list",".json")){//文件过滤
                    List<JsonNode> listNodes  = fileOperation(testFile[i]);
                   /* for(JsonNode node:listNodes){
                        DBObject dbObject =(DBObject) JSON.parse(node.toString());
                        mongoDao.insert(dbObject);
                        totalNum++;
                    }*/
                }
            } else if (testFile[i].isDirectory()) {
                readDirectory(testFile[i].getPath());
            } else {
                logger.error("文件读入有误");
            }
            //}
        }
        Long endTime = System.currentTimeMillis();
        Long time = endTime - startTime;
        logger.info("time={}",time);
        logger.info("totalNum={}",totalNum);

        return totalNum;
    }



    /**
     * list****.json 文件处理
     * @param file  json文件
     * @return     需要插入到数据库的jsonnode。
     */
    public  static List<JsonNode> fileOperation(File file){
        List<JsonNode> returnListNodes = new ArrayList<JsonNode>();
        logger.info("start filePath={}",file.getAbsolutePath().toString());
        InputStream is = null;
        try {
            if(file.length() <= 0){
                logger.error("文件大小为0");
                return returnListNodes;
            }
            is = new FileInputStream(file);
            ObjectMapper mapper = new ObjectMapper();
            JsonNode listNode = null;
            JsonNode node =  mapper.readTree(is);

            if(null != node){
                listNode = node.get("result_rows");
                if(null != listNode ){
                    logger.info("size={}",listNode.size());//需要插入的数据
                    for(int i = 0;i<listNode.size();i++){
                        JsonNode rowsNode =   listNode.get(i);
                        returnListNodes.add(rowsNode);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            logger.error("file does't exist ,message={}",e.getMessage());
        }catch (Exception e1){
            e1.printStackTrace();
            logger.error("file exception,message={}",e1.getMessage());
        }finally {
            if (null != is){
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error("close inputstream exception ={}",e.getMessage());
                }
            }
        }
        logger.info("end -----------------------------------");
        return returnListNodes;
    }




    /**
     * 过滤文件名的头部信息和文件名扩展名
     * @param file
     * @return
     */
    public static boolean fileFilter(File file,String prefix,String suffix){
        if(file != null ){
            String fileName = file.getName();
            logger.info("fileName={}",fileName);
            if(null != fileName ){
                boolean start = fileName.startsWith(prefix);
                boolean end = fileName.endsWith(suffix);
                if(start && end ){
                    return true;
                }
            }
        }
        return false;
    }



}
